/*
 * @Descripttion: 
 * @version: 
 * @Author: xuyang
 * @Date: 2021-05-13 23:24:47
 * @LastEditors: xuyang
 * @LastEditTime: 2021-05-18 00:53:03
 */
import {
  Provide,
} from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/orm';
import { User, } from '../entity/user';
import { Repository, Like, Not } from 'typeorm';
import { getMd5 } from '../util';
const dayjs = require('dayjs')
@Provide()
export class UserService {

  @InjectEntityModel(User)
  UserModel: Repository<User>;

  /**
   * 根据信息查询用户列表 
   * @param user 
   */
  async getAllUsersByParams (user: any){
    let params:any = new Object() ;
    let order = {
    }
    if(user.role){
      params.role = user.role;
    }
    if(user.status) {
      params.status = user.status;
    }
    if(user.username){
      params.username = Like(`%${user.username}%`);
    }
    if(!user.status){
      params.status = Not('2')
    }
    if(user.sorterKey){
      order = {};
      order[user.sorterKey] = user.sorterType;
    }else {
      order = {
        createTime: 'DESC'
      }
    }
    let list = await this.UserModel.find({
      where: params,
      skip: (user.page - 1) * user.pageSize,
      take: user.pageSize,
      order: order
    })
    let [userList, userCount] = await this.UserModel.findAndCount();
    console.log(userList);
    return {
      list: list,
      page: user.page,
      pageSize: user.pageSize,
      total: userCount
    }
  }
  async findAllUsers() {
    let [allUserDatas, usersCount] = await this.UserModel.findAndCount();
    return {
      content: allUserDatas,
      total: usersCount
    }
  }

  async getUserDetail(id) {
    let data = await this.UserModel.findOne({ id });
    return data
  }
  /**
   * 更新用户
   * @param params 
   * @returns 
   */
  async updateUser(params) {
    let data = await this.UserModel.findOne({ id: params.id });
    data = {
      ...data,
      ...params,
      updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
    }
    await this.UserModel.save(data)
    return {}
  }

  /**
   * 添加用户
   * @param params 
   * @returns 
   */
  async addNewUser(params) {
    params.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
    params.updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
    params.password = getMd5('123456');
    params.status = 1;
    let data = await this.UserModel.save(params);
    return data
  }
  /**
   * 根据用户名查找用户
   * @param params 
   * @returns 
   */
  async findOneUser(username: string) {
    let data = await this.UserModel.findOne({
      username: username
    });
    return data
  }
  /**
   * 更新密码
   */
  async updatePwd(params) {
    let data = await this.UserModel.findOne({
      username: params.username,
      password: params.oldPwd
    });
    if (data) {
      data.password = params.newPwd
      await this.UserModel.save(data)
      return true
    }
    return false
  }

}